import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
} from '@nestjs/common';
import { Response } from 'express';
/**
 * @desc 接口过滤器
 */

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp(); // 获取请求上下文
    const response = ctx.getResponse<Response>(); // 获取请求上下文中的 response 对象
    const status = exception.getStatus(); // 获取异常状态

    // 设置错误信息
    const message = exception.message
      ? exception.message
      : `${status > 500 ? 'Service Error' : 'Client Error'}`;

    const errorResponse = {
      data: {},
      message: message,
      code: -1,
      success: false,
    };

    const exceptionResponse: any = exception.getResponse();
    let validatorMessage = exceptionResponse;
    if (typeof validatorMessage === 'object') {
      validatorMessage = exceptionResponse.message[0];
    }
    // 设置返回的状态码，请求头，发错误信息
    response.status(status).json({
      code: status,
      message: exceptionResponse || message,
      success: false,
    });
    response.header('Content-Type', 'application/json; charset=utf-8');
    response.send(errorResponse);
  }
}
